package com.bawei.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.bawei.bean.AliPayBean;
import com.bawei.config.Alipay;
import com.bawei.pojo.Indent;
import com.bawei.pojo.Order;
import com.bawei.pojo.User;
import com.bawei.service.IndentService;
import com.bawei.service.PayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class PayServiceImpl implements PayService {
    /**日志对象*/
    private static final Logger logger = LoggerFactory.getLogger(PayServiceImpl.class);

    @Autowired
    private Alipay alipay;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private IndentService indentService;

    @Override
    public String aliPay(AliPayBean aliPayBean) throws AlipayApiException {
        logger.info("调用支付服务接口...");
        return alipay.pay(aliPayBean);
    }

    @Override
    public Integer addOrder(Integer middleId, Long snowFlakeId) {
        Order order = indentService.findIndent(middleId);
        Indent indent = new Indent();
        //获取用户id
        String s = redisTemplate.opsForValue().get("user");
        User user = JSONObject.parseObject(s, User.class);
        indent.setUserId(user.getUserId());
        //订单编号
        indent.setCode(String.valueOf(snowFlakeId));
        //购买总价格
        indent.setTotalPrice(order.getEventPrice());
        //订单详情
        String s1 = JSONObject.toJSONString(order);
        indent.setDetails(s1);
        //中间表id
        indent.setMiddleId(order.getMiddleId());
        //添加到数据库
        indentService.addOrder(indent);
        return indent.getOrderId();
    }
}
